/*
 * Copyright(c) 2018-? the original author[Wien(luweien@aliyun.com)] or authors.
 *
 */
package org.doll.it.session.util;

import org.doll.it.sequence.enums.BusinessTypeEnum;
import org.doll.it.sequence.impl.TwitterSnowFlake;
import org.doll.it.session.bo.DollUserBO;

/**
 * 当前用户工具类，可以全局获取当前用户
 * 
 * @author Wien(luweien@aliyun.com)
 *
 */
public class DollUserUtils {

	private static ThreadLocal<DollUserBO> local = new ThreadLocal<>();

	/**
	 * 获取当前用户，如果不存在，则返回一个匿名用户
	 * @return
	 */
	public static DollUserBO getCurrUser() {
		DollUserBO sessionUserVO = local.get();
		if (sessionUserVO == null) {
			sessionUserVO = newAnonymousUser();
		}
		return sessionUserVO;
	}

	/**
	 * 设置sessionId
	 * @param sessionId
	 */
	public static void setSessionId(String sessionId) {
		setCurrUser(newAnonymousUser(sessionId));
	}

	/**
	 * 设置当前用户
	 * @param currUserVO
	 */
	public static void setCurrUser(DollUserBO sessionUserVO) {
		if (sessionUserVO == null) {
			sessionUserVO = newAnonymousUser();
		}
		local.set(sessionUserVO);
	}

	/**
	 * 每次调用结束后，删除线程变量，防止内存泄漏
	 */
	public static void destroyCurrUser() {
		local.remove();
	}

	/**
	 * 是否已经登陆
	 * @return
	 */
	public static boolean isLogined() {
		return TwitterSnowFlake.validBusinessType(getCurrUser().getUserId(), BusinessTypeEnum.WEB_USER);
	}

	/**
	 * 获得会话Id
	 * @return
	 */
	public static String getSessionId() {
		return getCurrUser().getSessionId();
	}

	/**
	 * 获得用户Id
	 * @return
	 */
	public static Long getUserId() {
		return getCurrUser().getUserId();
	}

	/**
	 * 生成匿名用户
	 * @return
	 */
	private static DollUserBO newAnonymousUser() {
		return newAnonymousUser(null);
	}

	/**
	 * 生成匿名用户
	 * @return
	 */
	private static DollUserBO newAnonymousUser(String sessionId) {
		return new DollUserBO(sessionId, null);
	}
}
